const cuid = require("cuid");
const ws = require("ws");

let wss = null;

module.exports = function (server) {
    wss = new ws.WebSocketServer({ server });

    wss.on("connection", (ws, req) => {
        console.log("wss on connection");
        ws.on("message", function (data) {
            console.log("ws on message", wss, data.toString());
            // ws.send("test receive");
            wss.clients.forEach((item) => {
                if (ws !== item) {
                    item.send(data.toString());
                }
            });
        });

        ws.id = cuid();
        ws.send(JSON.stringify({ cmd: "init::open", res: { id: ws.id } }));
    });

    wss.on("close", function () {
        console.log("wss on close", arguments);
    });
};
